package com.arvato.admin01.service.token;

import com.arvato.admin01.Util.RandomUtil;
import com.arvato.admin01.Util.RedisUtil;
import com.arvato.admin01.constant.Constant;
import com.arvato.admin01.constant.ResponseCode;
import com.arvato.admin01.constant.ServerResponse;
import com.arvato.admin01.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.StrBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

import static java.awt.SystemColor.info;

@Service
@Slf4j
public class TokenServiceImpl implements TokenService {

    private static final String TOKEN_NAME = "token";

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public ServerResponse createToken() {
        String str = RandomUtil.UUID32();
        StrBuilder token = new StrBuilder();
        token.append(Constant.Redis.TOKEN_PREFIX).append(str);
        redisUtil.setEx(token.toString(), token.toString(), Constant.Redis.EXPIRE_TIME_MINUTE.longValue());
      //  System.out.println("key>>>"+redisUtil.get(token.toString()));
        return ServerResponse.success(token.toString());
    }

    @Override
    public void checkToken(HttpServletRequest request) {
        String token = request.getHeader(TOKEN_NAME);
        if (StringUtils.isBlank(token)) {// header中不存在token
            token = request.getParameter(TOKEN_NAME);
            if (StringUtils.isBlank(token)) {// parameter中也不存在token
                throw new ServiceException(ResponseCode.ILLEGAL_ARGUMENT.getMsg());
            }
        }
        if (!redisUtil.exists(token)) {
           // System.out.println("token>>>"+token);
            //System.out.println(redisUtil.exists(token));
            throw new ServiceException(ResponseCode.REPETITIVE_OPERATION.getMsg());
        }
        Long del = redisUtil.del(token);
        log.info("del>>>>>>>>"+del.toString());
        if (del <= 0) {
            throw new ServiceException(ResponseCode.REPETITIVE_OPERATION.getMsg());
        }
    }

}
